import React, { useState, useRef, useEffect } from 'react';
import { EditOutlined, DeleteOutlined, GithubOutlined, LaptopOutlined } from '@ant-design/icons';
import { Image, Tag, Card, Popconfirm, Spin, Tooltip, App, Empty, Col, Row } from 'antd';
import Edit from "./component/edit";
import api_project from "@/api/project/index";
import { getOptNameType } from "@/utils/dict";
import { useLocation } from "react-router-dom";
import { getRole } from "@/utils/localStorage"
import { RoleButton } from "@/components/RoleButton"
export default function My() {
  const { message, modal } = App.useApp();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const location = useLocation();
  const editEl = useRef();

  let classify = useRef('my')
  let isMounted = useRef(null)

  const openEdit = (_id, type) => {
    editEl.current.open(_id, type, classify.current);
  };

  const getlist = () => {
    setLoading(true)
    api_project.getList({ classify: classify.current }).then((res) => {
      if (!isMounted.current) return
      setLoading(false)
      setList(res.data)
    }).catch((err) => {
      setLoading(false)
    })
  }

  useEffect(() => {
    isMounted.current = true
    classify.current = location.pathname.slice(location.pathname.lastIndexOf('/') + 1)
    getlist();
    return () => {
      isMounted.current = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const remove = (_id) => {
    api_project.remove({ _id }).then((res) => {
      message.success("删除成功");
      getlist()
    })
  }

  const openProject = (projectUrl) => {
    if (projectUrl === '') { modal.info({ title: '提示', content: '非私人项目、不支持查看代码' }) }
    else if (projectUrl.includes('http')) { window.open(projectUrl) }
    else { modal.info({ title: '提示', content: projectUrl }) }
  }

  const getActions = (target) => {
    const role = getRole()
    if (role === 'admin') {
      return ([
        <Tooltip title="删除" >
          <Popconfirm title="删除该项目" description="您确定要删除该项目吗?" okText="Yes" cancelText="No" onConfirm={() => { remove(target._id) }}>
            <DeleteOutlined key="delete" />
          </Popconfirm>
        </Tooltip>,
        <Tooltip title="编辑" >
          <EditOutlined key="update" onClick={() => { openEdit(target._id, 'update') }} />
        </Tooltip>,
        <Tooltip title="项目地址">
          <LaptopOutlined key='projectUrl' onClick={() => { openProject(target.projectUrl) }} />
        </Tooltip>,
        <Tooltip title="代码地址">
          <GithubOutlined key='codeUrl' onClick={() => { openProject(target.codeUrl) }} />
        </Tooltip>,
      ])
    } else {
      return (
        [
          <Tooltip title="项目地址">
            <LaptopOutlined key='projectUrl' onClick={() => { openProject(target.projectUrl) }} />
          </Tooltip>,
          <Tooltip title="代码地址">
            <GithubOutlined key='codeUrl' onClick={() => { openProject(target.codeUrl) }} />
          </Tooltip>,
        ]
      )
    }
  }
  return (
    <>
      <RoleButton type="primary" role={getRole()} style={{ marginBottom: 10 }} onClick={() => { openEdit('-1', 'add') }}> 添加项目 </RoleButton>
      <Spin spinning={loading}>
        {list.length === 0 ? <Empty style={{ marginTop: '100px' }} /> :
          <Row gutter={16}>
            {list.map((item =>
              <Col key={item._id} span={6} flex={true} >
                <Card  style={{ width: '100%',marginBottom:'40px' }}
                  cover={
                    <>
                      <Image.PreviewGroup items={item.imgUrl}>
                        <Image fallback='https://pic.imgdb.cn/item/652f397bc458853aefff7856.jpg' style={{ objectFit: 'cover' }} height={200} src={item.coverUrl} />
                      </Image.PreviewGroup>
                    </>
                  }
                  actions={getActions(item)}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ fontSize: '18px', fontWeight: '700', marginBottom: '10px' }}>{item.name}</div>
                    <div style={{ color: '#8c8c8c' }}> {item.owner} </div>
                  </div>
                  {item.tag.map((item, index) => (
                    <Tag key={index}>{getOptNameType('code_type', item)}</Tag>
                  ))}
                  <Tag color={item.type === 'B' ? "#2db7f5" : '#87d068'}>to {item.type}</Tag>
                  <div className='s2' style={{ marginTop: '10px', color: '#8c8c8c', height: '44px' }}>{item.remark}</div>
                </Card>
              </Col>
            ))}
          </Row>
        }
      </Spin >
      <Edit callback={getlist} ref={editEl}></Edit>
    </>
  )
}
